package com.asset.modules.system.service.impl;


import com.asset.modules.system.mapper.RoleMapper;
import com.asset.modules.system.model.Company;
import com.asset.modules.system.model.Role;
import com.asset.modules.system.service.CompanyService;
import com.asset.modules.system.service.RoleService;
import com.asset.modules.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author asset
 * @since 2020-08-13
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    UserService userService;

    @Autowired
    CompanyService companyService;



    @Override
    public List<String> removeByIdsWithChecking(Collection<? extends Serializable> idList) {
        List<String> existIds = new ArrayList<>();
        for (Object id : idList) {
            String _id = String.valueOf(id);
            boolean isExist = userService.checkExistByRoleId(_id);
            if (isExist){
                existIds.add(_id);
            }else{
                removeById(_id);
            }
        }

        return existIds;
    }


    @Override
    public Role getRoleById(String id) {
        Role role = getById(id);
        Company c = companyService.getById(role.getCompanyId());
        role.setCompanyCode(c.getCompanyCode());
        role.setCompanyName(c.getCompanyName());
        return role;
    }

    @Override
    public List<Role> getAll() {
        List<Role> roles = list();
        List<Role> result = new ArrayList<>();
        if(roles.size()>0){
            for(Role r : roles){
                Company c = companyService.getById(r.getCompanyId());
                r.setCompanyCode(c.getCompanyCode());
                r.setCompanyName(c.getCompanyName());
                result.add(r);
            }
        }
        return result;
    }

    @Override
    public boolean isExist(String column, String name) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(column, name);
        Object result = getOne(queryWrapper);
        if(result!=null){
            return true;
        }
        return false;
    }
}
